﻿<?php
// We return json encoded data
header ('Content-type: application/json');

/**
 * Script used to remova a folder
 */

session_start();
require_once '../core/db.php';

if (!isset($_SESSION['user']))			// We can't remove a folder if no user is logged in
	die (json_encode (array ('error'=>'No user logged on')));

$sql = 'SELECT * FROM folder WHERE user=? and id=?';	// We must get the id of the parent folder for the folder to delete
$sth = $db->prepare ($sql);
$sth->execute (array ($_SESSION['user'], $_POST['id']));
if (!($row = $sth->fetch()))			// Unable to get the parent id, abort
	die (json_encode (array ('error'=>'Error during database operation')));
$parentid = $row['parent'];			// Store the id for the parent folder
$sth->fetchAll();						// Reuse the statement

// Keep the parentid in the same format as the folders we will return later on
$data[] = array ('id'=>$parentid, 'name'=>'parent');	

// SQL to delete the requested folder
$sql = 'DELETE FROM folders WHERE user=? AND id=?';	
$sth = $db->prepare ($sql);
$res = $sth->execute (array ($_SESSION['user'], $_POST['id']));		// Send the statement to the database
if ($res==0)	// No folder was deleted, send an error message
	die (json_encode (array ('error'=>'Error during database operation')));
	
// Now we need to return a list of folders remaining under the parent folder
$sql = 'SELECT name, id, user FROM folder WHERE user=? and parent=? order by name';
$sth = $db->prepare ($sql);
$sth->execute (array ($_SESSION['user'], $parentid));		// Get the list of child folders from the database
die (json_encode  (array_merge($data, $sth->fetchAll ())));	// Append the list of folder to the parent folder and return
?>